<?php
require_once 'config.php';

$sql = 'SELECT madt AS pid, tendt AS pname, giadt AS pprice, hinhdt as pimgurl FROM dienthoai WHERE (1 = 1) ';
$dk = '';

$bind = array();

if (isset($_GET['key'])) {
    $sql = file_get_contents(DB_DIR . 'search.sql');
    $bind['key'] = '%' . $_GET['key'] . '%';
} else {
    if(isset($_GET['lstManufacturer']) && $_GET['lstManufacturer'] !== 'null') {
        $sql .= 'AND mahsx = :mahsx ';

        $bind['mahsx'] = $_GET['lstManufacturer'];
    }

    if(isset($_GET['lstPrice']) && $_GET['lstPrice'] != 'null') {
        $base = (int)$_GET['lstPrice'];

        if ($base <= 1){
            $sql .= 'AND giadt <= :price ';
            $bind['price'] = 6000;
        } elseif ($base >= 7) {
            $sql .= 'AND giadt >= :price ';
            $bind['price'] = 16000;
        }
        else{
            $sql .= 'AND giadt  BETWEEN :pmin AND :pmax ';
            $max = $base * 2000 + 4000;
            $min = $base * 2000 + 2000;

            $bind['pmin'] = $min;
            $bind['pmax'] = $max;
        }
    }

    if(isset($_GET['txtProductName'])){
        $sql .= 'AND CONVERT(`tendt` USING utf8) LIKE :ptxtProductName';
        $bind['ptxtProductName'] ="%{$_GET['txtProductName']}%";
    }
}


$dt = new DienThoai();

$page =PGlobal::getLayoutTemplate();

$box = new Template(TEMPLATE_DIR.'home-dienthoai-box.html');

$data = $dt->run($sql, $bind);

/** phân trang */
$p = 1;

// Tổng số dòng dữ liệu
$rec_total = count($data);
if (isset($_GET['p'])) {
    $p = $_GET['p'];
}

$start = ($p - 1) * RECORD_PER_PAGE;

for ($j = $start; $j < $start + RECORD_PER_PAGE; $j++) {
    if ($j < $rec_total) {
        $row = $data[$j];
        $box['dienthoai-box-item'] .= PGlobal::getInstance()->renderBoxPhone($row);
    }
}
$pattern = '/([?&]?p=\d*)/e';
$querystring = preg_replace($pattern, '', $_SERVER['QUERY_STRING']);
$box['pagination'] = new Template(TEMPLATE_DIR . 'timkiem-phantrang.html');
for ($i = 1; $i <=  ceil($rec_total / RECORD_PER_PAGE); $i++) {
    $item = new Template(TEMPLATE_DIR . 'admin-dienthoai-pagination.html');
    $item['number'] = $i;
    if ($i == $p) {
        $item['extra'] = 'selected';
    }
    $item['href'] = '?' . $querystring .'&p=' . $i;
    $box['pagination']['paging'] .= $item->render();
}

$box['title'] = 'Kết quả tìm kiếm <em>(trang ' . $p .')</em>';
$page['content'] = $box->render();


$page->addCss('css/home.css');
$page->addCss('css/timkiem.css');

echo $page->render();
